<!--
 * @Description: 充电账单记录
 * @Author: py
 * @Date: 2024-03-03
-->
<script setup lang="ts" name="record-list">
import type { VxeGridProps, VxePagerEvents } from 'vxe-table'
import { useChargeSettleStoreWithOut } from '@/store/modules/charge-settle'
import { chargeAccountListApi, dictListApi, freezePayListApi } from '@fl/api/charge-settle'
import { SearchTable } from '@fl/components'
import { formatTime } from '@fl/utils'
import { cloneDeep } from 'lodash-es'
import { useRouter } from 'vue-router'

import StatementDialog from './components/statement-dialog.vue'

const router = useRouter()

const chargeSettleStore = useChargeSettleStoreWithOut()
const statementUpdated = computed(() => chargeSettleStore.getStatementUpdateMoment)

const activeTabName = ref('chargeList')
const isShowDialog = ref<boolean>(false)

type DictItem = {
    dictType: string
    dictValue: string | number
    dictLabel: string
}

const dictList = ref<DictItem[]>([])
const stationOptions = computed(() => {
    return dictList.value.filter(item => item.dictType === 'charge_station_type')
})
function getDictionaryDatas() {
    dictListApi({
        pageNum: 1,
        pageSize: 99999,
    }).then((res) => {
        dictList.value = res || []
    })
}
getDictionaryDatas()

const initialState = {
    orderCode: '',
    stationId: '',
    billCreateDate: undefined,
}

const queryState = ref(cloneDeep(initialState))

function formatDate({ cellValue }) {
    return formatTime(cellValue, 'yyyy-MM-dd')
}

function formatPrice({ cellValue }) {
    if (cellValue === null) {
        return ''
    }

    return cellValue === 0 ? '¥ 0' : `¥ ${Number.parseFloat(cellValue).toFixed(2)}`
}
const chargeGridOptions = reactive<VxeGridProps>({
    align: 'left',
    border: 'inner',
    columnConfig: {
        resizable: false,
    },
    columns: [
        { fixed: 'left', field: 'orderCode', minWidth: 140, title: '订单ID' },
        { field: 'operatorName', minWidth: 160, title: '商户名称' },
        { field: 'stationName', minWidth: 180, title: '站点名称' },
        { field: 'billGenerationTime', formatter: formatDate, title: '结算账单日期', width: 120 },
        { field: 'chargeStartTime', title: '充电开始时间', width: 160 },
        { field: 'chargeEndTime', title: '充电完成时间', width: 160 },
        { field: 'chargeAmount', minWidth: 120, title: '订单充电量' },
        { align: 'right', field: 'totalAmount', formatter: formatPrice, title: '实收总金额', width: 120 },
        { align: 'right', field: 'chargeFee', formatter: formatPrice, title: '实收电费', width: 120 },
        { align: 'right', field: 'serviceFee', formatter: formatPrice, title: '实收服务费', width: 120 },
        { align: 'right', field: 'platformServiceFee', formatter: formatPrice, title: '平台技术服务费', width: 135 },
    ],
    data: [],
    loading: false,
    maxHeight: 450,
    minHeight: 250,
    rowConfig: {
        isHover: true,
        keyField: 'id',
    },
    showOverflow: false,
})

const chargeTablePage = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0,
})

type QueryParams = {
    orderCode: string
    stationId: string
    pageNum: number
    pageSize: number
    billGenerationStartTime?: string
    billGenerationEndTime?: string
}
function getChargeList() {
    chargeGridOptions.loading = true

    const { orderCode, billCreateDate, stationId } = queryState.value
    const oParams: QueryParams = {
        pageNum: chargeTablePage.currentPage,
        pageSize: chargeTablePage.pageSize,
        orderCode,
        stationId,
    }
    if (billCreateDate) {
        oParams.billGenerationStartTime = day(billCreateDate[0]).format('YYYY-MM-DD 00:00:00')
        oParams.billGenerationEndTime = day(billCreateDate[1]).format('YYYY-MM-DD 23:59:59')
    }

    chargeAccountListApi(oParams).then((res) => {
        const { records, total } = res
        chargeTablePage.total = +total
        chargeGridOptions.data = records
    }).finally(() => {
        chargeGridOptions.loading = false
    })
}
getChargeList()

const chargePageChange: VxePagerEvents.PageChange = ({ currentPage, pageSize }) => {
    chargeTablePage.currentPage = currentPage
    chargeTablePage.pageSize = pageSize
    getChargeList()
}

const freezePayGridOptions = reactive<VxeGridProps>({
    align: 'left',
    border: 'inner',
    columnConfig: {
        resizable: false,
    },
    columns: [
        { fixed: 'left', field: 'operatorName', minWidth: 160, title: '商户名称' },
        { field: 'stationName', minWidth: 180, title: '站点名称' },
        { field: 'orderCode', minWidth: 140, title: '订单ID' },
        { field: 'changeType', minWidth: 120, title: '变动类型' },
        // { field: 'contractId', minWidth: 140, title: '合同ID' },
        // { field: 'applicationId', minWidth: 140, title: '发票申请单ID' },
        // { field: 'updateTime', title: '操作时间', width: 160 },
        { field: 'billGenerationTime', formatter: formatDate, title: '结算日期', width: 120 },
        { align: 'right', field: 'parkingFee', formatter: formatPrice, title: '金额', width: 120 },
        { field: 'feeType', minWidth: 140, title: '费用类型' },
    ],
    data: [],
    loading: false,
    maxHeight: 450,
    minHeight: 250,
    rowConfig: {
        isHover: true,
        keyField: 'id',
    },
    showOverflow: false,
})

const freezePayTablePage = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0,
})

function getFreezePayList() {
    freezePayGridOptions.loading = true

    const { orderCode, billCreateDate, stationId } = queryState.value

    const oParams: QueryParams = {
        pageNum: freezePayTablePage.currentPage,
        pageSize: freezePayTablePage.pageSize,
        orderCode,
        stationId,
    }
    if (billCreateDate) {
        oParams.billGenerationStartTime = day(billCreateDate[0]).format('YYYY-MM-DD 00:00:00')
        oParams.billGenerationEndTime = day(billCreateDate[1]).format('YYYY-MM-DD 23:59:59')
    }

    freezePayListApi(oParams).then((res) => {
        const { records, total } = res
        freezePayTablePage.total = +total
        freezePayGridOptions.data = records
    }).finally(() => {
        freezePayGridOptions.loading = false
    })
}
getFreezePayList()

const freezePayPageChange: VxePagerEvents.PageChange = ({ currentPage, pageSize }) => {
    freezePayTablePage.currentPage = currentPage
    freezePayTablePage.pageSize = pageSize
    getFreezePayList()
}

function handleSearch() {
    chargeTablePage.currentPage = 1
    if (activeTabName.value === 'chargeList') {
        getChargeList()
    }
    else {
        getFreezePayList()
    }
}
function handleReset() {
    queryState.value = cloneDeep(initialState)
    chargeTablePage.currentPage = 1
    chargeTablePage.pageSize = 10
    if (activeTabName.value === 'chargeList') {
        getChargeList()
    }
    else {
        getFreezePayList()
    }
}

watch(statementUpdated, () => {
    handleReset()
})

function toImport() {
    router.push({
        name: 'record-import',
        query: {
            importType: activeTabName.value,
        },
    })
}
function toCreate() {
    isShowDialog.value = true
}
</script>

<template>
    <ElCard shadow="never"
            class="mb-20 border-none"
    >
        <el-form inline
                 class="search-form"
                 :model="queryState"
        >
            <el-form-item label="订单ID">
                <el-input v-model="queryState.orderCode"
                          placeholder="请输入"
                          clearable
                />
            </el-form-item>

            <el-form-item label="充电站名称">
                <el-select v-model="queryState.stationId"
                           clearable
                >
                    <el-option v-for="item in stationOptions"
                               :key="item.dictValue"
                               :label="item.dictLabel"
                               :value="item.dictValue"
                    />
                </el-select>
            </el-form-item>

            <el-form-item label="结算单日期"
                          class="w-350"
            >
                <el-date-picker v-model="queryState.billCreateDate"
                                unlink-panels
                                type="daterange"
                                value-format="YYYY-MM-DD"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期"
                />
            </el-form-item>

            <el-form-item class="search-btns">
                <el-button type="primary"
                           @click="handleSearch"
                >
                    搜索
                </el-button>

                <el-button @click="handleReset">
                    重置
                </el-button>
            </el-form-item>
        </el-form>
    </ElCard>

    <ElCard shadow="never"
            class="border-none"
    >
        <el-button type="primary"
                   class="mb-10"
                   @click="toImport"
        >
            <!-- <span class="i-iconamoon:upload mr-4" /> -->
            <span class="vxe-icon-download mr-4" />

            <span class="lh-16">导入</span>
        </el-button>

        <el-button type="primary"
                   class="mb-10"
                   @click="toCreate"
        >
            <span class="i-mingcute:add-line mr-4" />

            <span class="lh-16">生成结算单</span>
        </el-button>

        <el-tabs v-model="activeTabName">
            <el-tab-pane label="充电账单明细"
                         name="chargeList"
            >
                <SearchTable v-bind="chargeGridOptions"
                             v-model:pager="chargeTablePage"
                             @page-change="chargePageChange"
                />
            </el-tab-pane>

            <el-tab-pane label="冻结及赔付账单明细"
                         name="freezeAndPayList"
            >
                <SearchTable v-bind="freezePayGridOptions"
                             v-model:pager="freezePayTablePage"
                             @page-change="freezePayPageChange"
                />
            </el-tab-pane>
        </el-tabs>
    </ElCard>

    <StatementDialog v-model:visible="isShowDialog"
                     @success="handleSearch"
    />
</template>

<style lang="less" scoped>
@import '../custom.less';

.search-form {
    :deep(.el-form-item) {
        width: 300px;
        margin-right: 20px;
        margin-bottom: 0;

        &.w-350 {
            width: 350px;
        }

        &.search-btns {
            width: auto;
            margin-right: 0;
        }
    }
}

:deep(.el-tabs__header) {
    margin: 0 0 20px;
}

:deep(.el-tabs__nav-wrap) {
    &::after {
        display: none;
    }

    .el-tabs__item {
        padding: 0 10px;
    }
}
</style>
